import random


from rest_framework import status
from rest_framework.views import APIView
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework.response import Response

from celery_tasks.sms.tasks import send_sms_code
from . import constants


class SMSCodeView(APIView):

    def get(self, request, mobile):

        # 1.创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            sms_code = redis_conn.get("sms_%s" % mobile).decode()
            return Response({'message': f'验证码仍可用,验证码是{sms_code}'}, status=status.HTTP_400_BAD_REQUEST)
        # 2.生成验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 3.利用容联云通讯发送验证码
        # CCP().send_template_sms(mobile, [f'{sms_code}', constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        send_sms_code.delay(mobile, sms_code)

        # 4.把验证码存到redis数据库 pipeline 减少了redis的连接次数
        p1 = redis_conn.pipeline()
        p1.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        p1.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        p1.execute()
        # 5.响应
        return Response({'message': f'发送成功,验证码是{sms_code}'}, status=status.HTTP_200_OK)

    def post(self, request):
        pass


